package com.chanzany.adapter.springMVCAdapter;

import java.util.ArrayList;
import java.util.List;

public class DispatcherServlet {
    public static List<HandlerAdapter> handlerAdapters = new ArrayList<>();
    public DispatcherServlet(){
        handlerAdapters.add(new AnnotationHandlerAdapter());
        handlerAdapters.add(new SimpleHandlerAdapter());
        handlerAdapters.add(new HttpHandlerAdapter());
    }
    public void doDispatch(){
        //此处模拟SpringMVC从request取handler对象
        //适配器可以获得到期望的controller
//        Controller controller = new HttpController();
        Controller controller = new SimpleController();
        //得到对应的适配器
        HandlerAdapter adapter = getHandler(controller);
        //通过适配器执行对应的controller方法
        adapter.handle(controller);
    }

    private HandlerAdapter getHandler(Object handler) {
        for (HandlerAdapter adapter : handlerAdapters) {
            if (adapter.support(handler)){
                return adapter;
            }
        }
        throw new RuntimeException("No adapter for handler [" + handler +
                "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
    }

    public static void main(String[] args) {
        new DispatcherServlet().doDispatch();
    }

}
